package com.cxlin.cwanandroid.ui.browser

import android.graphics.Bitmap
import android.os.Bundle
import android.util.Log
import android.view.View
import com.cxlin.base.BaseActivity
import com.cxlin.base.ext.binding
import com.cxlin.base.ext.extraActivity
import com.cxlin.cwanandroid.R
import com.cxlin.cwanandroid.databinding.ActivityBrowserBinding
import com.tencent.smtt.sdk.WebChromeClient
import com.tencent.smtt.sdk.WebView

/**
 *
 * @Author: chenxunlin
 * @Date: 2024/4/29 9:58
 */
class BrowserActivity : BaseActivity() {

    private val binding by binding<ActivityBrowserBinding>(R.layout.activity_browser)
    private val url by extraActivity<String>("url")

    override fun initView(savedInstanceState: Bundle?) {
        binding.mToolbar.title = getString(R.string.is_loading)
        binding.mToolbar.setNavigationIcon(R.drawable.arrow_back)
        setSupportActionBar(binding.mToolbar)
        initWebView()
    }

    override fun initData(savedInstanceState: Bundle?) {
        binding.mToolbar.setNavigationOnClickListener {
            onBackPressed()
        }
    }

    override fun observeStateAndEvent() {
    }

    private fun initWebView(){
        binding.progressBar.progressDrawable = getDrawable(R.drawable.color_progressbar)
        binding.webView.run {
            webViewClient = object : com.tencent.smtt.sdk.WebViewClient() {

                override fun onPageStarted(p0: WebView?, p1: String?, p2: Bitmap?) {
                    super.onPageStarted(p0, p1, p2)
                    binding.progressBar.visibility = View.VISIBLE
                }

                override fun onPageFinished(p0: WebView?, p1: String?) {
                    super.onPageFinished(p0, p1)
                    binding.progressBar.visibility = View.GONE
                }
            }

            webChromeClient = object : WebChromeClient() {
                override fun onProgressChanged(p0: WebView?, p1: Int) {
                    super.onProgressChanged(p0, p1)
                    binding.progressBar.progress = p1
                    Log.e("browser", p1.toString())
                }

                override fun onReceivedTitle(p0: WebView?, p1: String?) {
                    super.onReceivedTitle(p0, p1)
                    p1?.let { binding.mToolbar.title = p1 }
                }

            }
        }
        binding.webView.loadUrl(url)
    }

    override fun onBackPressed() {
        if(binding.webView.canGoBack()) binding.webView.goBack()
        else super.onBackPressed()
    }
}